import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { Card, Row, Col, Statistic, Table, Spin, message, Button, Space } from 'antd';
import { ArrowUpOutlined, ArrowDownOutlined, ReloadOutlined } from '@ant-design/icons';
import api from '../services/api';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

interface FundDetail {
  id: number;
  code: string;
  name: string;
  category: string;
  risk_level: number;
  manager: string;
  company: string;
  establishment_date: string;
  management_fee: number;
  custody_fee: number;
  subscription_fee: number;
  redemption_fee: number;
  min_investment: number;
  status: string;
}

interface PriceData {
  id: number;
  price_date: string;
  net_value: number;
  accumulated_value: number;
  daily_return: number;
}

interface PerformanceData {
  period: string;
  return_rate: number;
  volatility: number;
  sharpe_ratio: number;
  max_drawdown: number;
}

const FundDetail: React.FC = () => {
  const { code } = useParams<{ code: string }>();
  const [fundDetail, setFundDetail] = useState<FundDetail | null>(null);
  const [priceData, setPriceData] = useState<PriceData[]>([]);
  const [performanceData, setPerformanceData] = useState<PerformanceData[]>([]);
  const [loading, setLoading] = useState(true);

  const priceColumns: ColumnsType<PriceData> = [
    {
      title: '日期',
      dataIndex: 'price_date',
      key: 'price_date',
      width: 120,
    },
    {
      title: '单位净值',
      dataIndex: 'net_value',
      key: 'net_value',
      width: 120,
      render: (value: any) => {
        if (value === null || value === undefined) return '-';
        const numValue = typeof value === 'string' ? parseFloat(value) : value;
        return isNaN(numValue) ? '-' : numValue.toFixed(4);
      },
    },
    {
      title: '累计净值',
      dataIndex: 'accumulated_value',
      key: 'accumulated_value',
      width: 120,
      render: (value: any) => {
        if (value === null || value === undefined) return '-';
        const numValue = typeof value === 'string' ? parseFloat(value) : value;
        return isNaN(numValue) ? '-' : numValue.toFixed(4);
      },
    },
    {
      title: '日收益率(%)',
      dataIndex: 'daily_return',
      key: 'daily_return',
      width: 120,
      render: (value: number) => {
        if (value === null || value === undefined) return '-';
        const color = value > 0 ? '#f50' : value < 0 ? '#87d068' : '#666';
        const numValue = typeof value === 'string' ? parseFloat(value) : value;
        if (isNaN(numValue)) return '-';
        return <span style={{ color }}>{(numValue * 100).toFixed(2)}%</span>;
      },
    },
  ];

  const performanceColumns: ColumnsType<PerformanceData> = [
    {
      title: '统计周期',
      dataIndex: 'period',
      key: 'period',
      width: 100,
    },
    {
      title: '收益率(%)',
      dataIndex: 'return_rate',
      key: 'return_rate',
      width: 120,
      render: (value: number) => {
        if (value === null || value === undefined) return '-';
        const color = value > 0 ? '#f50' : value < 0 ? '#87d068' : '#666';
        return <span style={{ color }}>{(value * 100).toFixed(2)}%</span>;
      },
    },
    {
      title: '波动率(%)',
      dataIndex: 'volatility',
      key: 'volatility',
      width: 120,
      render: (value: number) => value ? `${(value * 100).toFixed(2)}%` : '-',
    },
    {
      title: '夏普比率',
      dataIndex: 'sharpe_ratio',
      key: 'sharpe_ratio',
      width: 120,
      render: (value: number) => value?.toFixed(2) || '-',
    },
    {
      title: '最大回撤(%)',
      dataIndex: 'max_drawdown',
      key: 'max_drawdown',
      width: 120,
      render: (value: number) => value ? `${(value * 100).toFixed(2)}%` : '-',
    },
  ];

  const fetchFundDetail = async () => {
    if (!code) return;
    
    setLoading(true);
    try {
      // 获取基金基本信息
      const detailResponse = await api.get(`/api/data-service/funds/${code}/`);
      setFundDetail(detailResponse.data);

      // 获取价格数据（历史净值）
      const priceResponse = await api.get(`/api/data-service/funds/${code}/net-values/`, {
        params: { limit: 30 }
      });
      setPriceData(priceResponse.data.results || priceResponse.data);

      // 获取业绩数据
      const performanceResponse = await api.get(`/api/data-service/funds/${code}/performance/`);
      setPerformanceData(performanceResponse.data.results || performanceResponse.data);
    } catch (error) {
      message.error('获取基金详情失败');
      console.error('Error fetching fund detail:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleRefresh = () => {
    fetchFundDetail();
  };

  useEffect(() => {
    fetchFundDetail();
  }, [code]);

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!fundDetail) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <p>未找到基金信息</p>
      </div>
    );
  }

  const latestPrice = priceData[0];
  const previousPrice = priceData[1];
  const dailyChange = latestPrice && previousPrice 
    ? ((latestPrice.net_value - previousPrice.net_value) / previousPrice.net_value * 100)
    : 0;

  return (
    <div style={{ padding: '24px' }}>
      <Card 
        title={`${fundDetail.name} (${fundDetail.code})`}
        extra={
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
            loading={loading}
          >
            刷新
          </Button>
        }
        style={{ marginBottom: '24px' }}
      >
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="单位净值"
              value={latestPrice?.net_value || 0}
              precision={4}
              valueStyle={{ color: dailyChange > 0 ? '#3f8600' : dailyChange < 0 ? '#cf1322' : '#666' }}
              prefix={dailyChange > 0 ? <ArrowUpOutlined /> : dailyChange < 0 ? <ArrowDownOutlined /> : null}
              suffix={`(${dailyChange.toFixed(2)}%)`}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="累计净值"
              value={latestPrice?.accumulated_value || 0}
              precision={4}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="风险等级"
              value={fundDetail.risk_level}
              suffix="级"
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="最小投资金额"
              value={fundDetail.min_investment}
              precision={2}
              prefix="¥"
            />
          </Col>
        </Row>
        
        <Row gutter={[16, 16]} style={{ marginTop: '24px' }}>
          <Col xs={24} sm={12}>
            <p><strong>基金经理：</strong>{fundDetail.manager}</p>
            <p><strong>基金公司：</strong>{fundDetail.company}</p>
            <p><strong>成立日期：</strong>{fundDetail.establishment_date}</p>
          </Col>
          <Col xs={24} sm={12}>
            <p><strong>管理费率：</strong>{(fundDetail.management_fee * 100).toFixed(2)}%</p>
            <p><strong>托管费率：</strong>{(fundDetail.custody_fee * 100).toFixed(2)}%</p>
            <p><strong>申购费率：</strong>{(fundDetail.subscription_fee * 100).toFixed(2)}%</p>
            <p><strong>赎回费率：</strong>{(fundDetail.redemption_fee * 100).toFixed(2)}%</p>
          </Col>
        </Row>
      </Card>

      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card title="历史净值" style={{ height: '400px' }}>
            <Table
              columns={priceColumns}
              dataSource={priceData}
              rowKey="id"
              pagination={{
                pageSize: 10,
                showSizeChanger: false,
              }}
              scroll={{ y: 280 }}
              size="small"
            />
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="业绩表现" style={{ height: '400px' }}>
            <Table
              columns={performanceColumns}
              dataSource={performanceData}
              rowKey="period"
              pagination={false}
              scroll={{ y: 280 }}
              size="small"
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default FundDetail;